package org.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.mysql.cj.util.StringUtils;
import lombok.Getter;
import org.example.entity.Book;
import org.example.excel.BookExcel;
import org.example.excel.BookExcelListener;
import org.example.exception.ErrorEnum;
import org.example.exception.ServiceException;
import org.example.mapper.BookMapper;
import org.example.param.BookParam;
import org.example.service.BookService;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Getter
@Service
public class BookServiceImpl implements BookService {

    @Resource
    BookMapper bookMapper;



    @Override
    public Map<String, Object> change(Book book) {
        bookMapper.updateById(book);
        return success();
    }

   @Override
    public Object check(BookParam param) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isNullOrEmpty(param.getName())) {
            queryWrapper.like("name", param.getName());
        }
        if (StringUtils.isNullOrEmpty(param.getName())&&!StringUtils.isNullOrEmpty(param.getISBN())) {
            queryWrapper.eq("ISBN", param.getISBN());
        }
        if (StringUtils.isNullOrEmpty(param.getISBN())&&!StringUtils.isNullOrEmpty(param.getPress())) {
            queryWrapper.like("Press", param.getPress());
        }

        // 创建分页对象，传入当前页码和每页大小
        IPage<Book> page = new Page<>(param.getCurrent(), param.getSize());

        // 执行分页查询
        IPage<Book> resultPage = bookMapper.selectPage(page, queryWrapper);

        return success(resultPage);
    }


    @Override
    public Map<String, Object>save(Book book) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ISBN", book.getISBN());
        if (bookMapper.exists(queryWrapper)) {
            throw new ServiceException(ErrorEnum.MATERIAL_EXISTS);
        }
        bookMapper.insert(book);
        return success();
    }

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public Map<String, Object> receive(MultipartFile file) {
        Map map = new HashMap();
        String filename = file.getOriginalFilename();

        BookExcelListener listener = new BookExcelListener();
        try {

            long m1 = System.currentTimeMillis();
            EasyExcel.read(file.getInputStream(), BookExcel.class, listener)
                    .sheet().doRead();
            long m2 = System.currentTimeMillis();

            List<BookExcel> list = listener.getList();

            // System.out.println(list);
            // 这里插入最核心的步骤: 数据批量入库
            String sql = "insert into Book (name, ISBN, author, press,publication_date,category) values (?,?,?,?,?,?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    BookExcel Book = list.get(i);
                    ps.setObject(1, Book.getBookName());
                    ps.setObject(2, Book.getIsbn());
                    ps.setObject(3, Book.getAuthor());
                    ps.setObject(4, Book.getPress());
                    ps.setObject(5, Book.getPublishDate());
                    ps.setObject(6, Book.getCategory());
                }
                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });
            long m3 = System.currentTimeMillis();
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "-1");
            map.put("message", "操作失败,请检查文件格式或是否有已存在的商品");
            return map;
        }
    }

}






